<!--  -->
<template>
  <div>
    <div class="row at-row">
      <div class="col-md-12 formstyle">
        <h2>基本信息</h2>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="ruleForm"
        >
          <el-form-item label="会议名称" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="会议描述" prop="desc">
            <el-input v-model="ruleForm.desc"></el-input>
          </el-form-item>
          <el-form-item label="会议室" prop="room">
            <el-select v-model="ruleForm.room" placeholder="请选择会议室">
              <el-option
                :label="item.name"
                :value="item.name"
                v-for="(item,index) in roomlist"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="会议时间" required>
            <el-form-item prop="date">
              <el-date-picker
                v-model="ruleForm.date"
                type="datetimerange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['12:00:00']"
                value-format="timestamp"
              ></el-date-picker>
            </el-form-item>
          </el-form-item>
          <el-form-item label="会议提醒" prop="notice">
            <el-switch v-model="ruleForm.notice"></el-switch>
          </el-form-item>
          <el-form-item label="会议性质" prop="type">
            <el-checkbox-group v-model="ruleForm.type">
              <el-checkbox label="每周例会" name="type"></el-checkbox>
              <el-checkbox label="紧急会议" name="type"></el-checkbox>
              <el-checkbox label="线下主题活动" name="type"></el-checkbox>
              <el-checkbox label="其他" name="type"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="参会成员" prop="member">
            <at-button type="primary" @click="choosemember">选择成员</at-button>
            <at-collapse simple accordion :value="0" v-if="memberlistshow.length!=0">
              <at-collapse-item
                v-for="(item, index) in memberlistshow"
                :key="index"
                :title="item.groupname"
              >
                <div class="collapsecontent">
                  <at-tag
                    color="info"
                    v-for="(value,memberindex) in item.members"
                    :key="memberindex"
                    style="margin:0 5px"
                  >{{ value.nick }}</at-tag>
                </div>
              </at-collapse-item>
            </at-collapse>
          </el-form-item>
        </el-form>
      </div>
      <div class="col-md-12 formstyle">
        <h2>详细信息</h2>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="ruleForm"
        >
          <el-form-item label="额外需求" prop="resource">
            <el-radio-group v-model="ruleForm.resource">
              <el-radio label="茶点布置"></el-radio>
              <el-radio label="水果布置"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="tip">
            <el-input type="textarea" v-model="ruleForm.tip"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <at-modal v-model="choosememberdialog">
      <div slot="header" style="text-align:center;">
        <span>选择参会成员</span>
      </div>
      <div>
        <div class="dialogcontent" v-for="(item,index) in memberlist" :key="index">
          <div class="groupname">
            <at-checkbox
              v-model="item.groupnamechoose"
              :label="item.groupname"
              @on-change="handlechooseallgroup(item.groupnamechoose,item.groupname,item.member)"
            >{{item.groupname}}</at-checkbox>
          </div>
          <div class="members">
            <at-checkbox-group
              v-model="meetingmembers"
              @on-change="setgroupname($event,item.groupname)"
            >
              <at-checkbox
                :label="memberitem"
                v-for="(memberitem,memberindex) in item.member"
                :key="memberindex"
              >{{memberitem.nick}}</at-checkbox>
            </at-checkbox-group>
          </div>
        </div>
      </div>
      <div slot="footer">
        <at-button @click="choosememberdialog=false">取消</at-button>
        <at-button type="primary" @click="submitchoosemember">确定</at-button>
      </div>
    </at-modal>
  </div>
</template>

<script>
import { getArrDifference } from "../../assets/js/common";
import { setCookie, getCookie, removeCookie } from "../../assets/js/common";
import { fetch, post } from "../../config/request";
import { mapMutations, mapState } from "vuex";
import axios from "axios";
export default {
  data() {
    return {
      ruleForm: {
        name: "",
        date: "",
        notice: false,
        type: [],
        room: "",
        resource: "",
        desc: "",
        member: []
      },
      rules: {
        name: [{ required: true, message: "请输入会议名称", trigger: "blur" }],
        room: [{ required: true, message: "请选择会议室", trigger: "change" }],
        date: [
          {
            type: "date",
            required: true,
            message: "请选择日期",
            trigger: "change"
          }
        ],
        date2: [
          {
            type: "date",
            required: true,
            message: "请选择时间",
            trigger: "change"
          }
        ],
        type: [
          {
            type: "array",
            message: "请至少选择一个会议性质",
            trigger: "change"
          }
        ],
        desc: [{ required: true, message: "请填写会议概要", trigger: "blur" }]
      },
      memberlist: [],
      choosememberdialog: false,
      meetingmembers: [],
      groupnamechoose: "",
      groups: [],
      chooselist: [],
      editsinglechoose: {},
      groupname: "",
      memberlistshow: [],
      roomlist: [],
      mymemberlist: []
    };
  },
  computed: {
    ...mapState(["rooms", "meetings"])
  },
  components: {},
  created() {
    let roomstate = this.$store.state.rooms;
    if (roomstate.length == 0) {
      this.getlist();
    } else {
      this.roomlist = this.rooms;
      this.totalroomlist = JSON.parse(JSON.stringify(this.roomlist));
    }
    this.getuserlist();
    if (this.$route.query.name) {
      this.ruleForm.room = this.$route.query.name;
    }
  },
  watch: {
    meetingmembers(newval, oldval) {
      let changestr = getArrDifference(newval, oldval);
      if (newval.length > oldval.length) {
        this.editsinglechoose = {
          action: "add",
          value: changestr[0]
        };
      } else {
        this.editsinglechoose = {
          action: "delete",
          value: changestr[0]
        };
      }
      this.choosesinglemember(this.groupname);
      console.log(this.editsinglechoose);
    }
  },

  methods: {
    getuserlist() {
      fetch("/api/api/user/users").then(res => {
        console.log(res.data);
        let member = [];
        res.data.users.list.map((item, index) => {
          member.push({
            nick: item.nick,
            UUID: item.UUID
          });
        });
        this.memberlist.push({
          groupname: "开发组",
          member: member
        });
        this.mymemberlist = member;
      });
    },
    async getlist() {
      this.roomlist = await this.getrooms();
      this.changeRooms({
        rooms: this.roomlist
      });
    },
    getrooms() {
      return new Promise((resolve, reject) => {
        fetch("/api/api/user/room").then(res => {
          let room = res.data.rooms.list;
          resolve(room);
        });
      });
    },
    submitchoosemember() {
      this.choosememberdialog = false;
      this.chooselist = this.chooselist.filter(item => {
        return item.members.length != 0;
      });
      this.memberlistshow = JSON.parse(JSON.stringify(this.chooselist));
    },
    setgroupname(value, groupname) {
      this.groupname = groupname;
    },
    choosesinglemember(groupname) {
      if (groupname) {
        let action = this.editsinglechoose.action;
        let list = this.chooselist;
        switch (action) {
          case "add":
            let flag = false;
            for (let i = 0; i < list.length; i++) {
              if (list[i].groupname == groupname) {
                flag = true;
                list[i].members.push(this.editsinglechoose.value);
                break;
              }
            }
            if (!flag) {
              let pushdata = {
                groupname: groupname,
                members: [this.editsinglechoose.value]
              };
              list.push(pushdata);
            }
            break;
          case "delete":
            for (let i = 0; i < list.length; i++) {
              if (list[i].groupname == groupname) {
                list[i].members = list[i].members.filter(item => {
                  return item != this.editsinglechoose.value;
                });
              }
            }
            break;
        }
        this.chooselist = list;
      }
    },
    handlechooseallgroup(ifchoose, groupname, members) {
      if (ifchoose) {
        // this.meetingmembers = this.meetingmembers.concat(members);
        // this.chooselist.push({
        //   groupname: groupname,
        //   members: members
        // });
        let flag = false;
        this.meetingmembers = this.meetingmembers.concat(members);
        this.chooselist.map(item => {
          if (item.groupname == groupnamechoose) {
            flag = true;
            item.members = members;
          }
        });
        if (!flag) {
          this.chooselist.push({
            groupname: groupname,
            members: members
          });
        }
      } else {
        let memberindex = "";
        members.map((item, index) => {
          memberindex = this.meetingmembers.indexOf(item);
          this.meetingmembers.splice(memberindex, 1);
        });
        this.chooselist = this.chooselist.filter(item => {
          return item.groupname != groupname;
        });
      }
      this.meetingmembers = [...new Set(this.meetingmembers)];

      if (this.groups.indexOf(groupname) == -1) {
      }
    },
    choosemember() {
      this.choosememberdialog = true;
      //this.getgroups();
    },
    getgroups() {
      fetch("/api/api/user/groups").then(res => {
        this.groups = data.data.groups.list;
      });
    },
    generateUUID() {
      var d = new Date().getTime();
      if (window.performance && typeof window.performance.now === "function") {
        d += performance.now(); //use high-precision timer if available
      }
      var uuid = "xxxxxxxxxxxxxxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, function(
        c
      ) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
      });
      return uuid;
    },
    submitForm(formName) {
      let formdata = this.ruleForm;
      let users = [];
      let UUID = "";

      this.mymemberlist.map(item => {
        users.push(item.UUID);
        if (item.nick == getCookie("username")) {
          UUID = item.UUID;
        }
      });
      let addr = "";
      this.roomlist.map((item, index) => {
        if (item.name == formdata.room) {
          addr = item.addr;
        }
      });
      let params = {
        ID: this.generateUUID(),
        name: formdata.name,
        desc: formdata.desc,
        startTime: formdata.date[0],
        endTime: formdata.date[1],
        room: {
          name: formdata.room,
          addr: addr
        },
        host: {
          nick: getCookie("username")
        },
        users: this.meetingmembers
      };
      let meetings = JSON.parse(JSON.stringify(this.meetings));
      meetings.push(params);
      let that = this;
      this.$refs[formName].validate(valid => {
        if (valid) {
          let listid = [];
          let roomid = "";
          let myroom = {};
          that.roomlist.map(item => {
            if (item.name == formdata.room) {
              roomid = item.ID;
            }
          });
          // let param = new URLSearchParams();
          // param.append("room", roomid);
          // param.append("host", UUID);
          // param.append("name", formdata.name);
          // param.append("desc", formdata.desc);
          // param.append("startTime", formdata.date[0]);
          // param.append("endTime", formdata.date[1]);
          // axios
          //   .post("/api/api/user/meeting", param, {
          //     headers: {
          //       Authorization: "Bearer " + getCookie("token"),
          //       "Content-Type": "application/x-www-form-urlencoded"
          //     }
          //   })
          //   .then(res => {
          //     console.log(res);
          //   })
          //   .catch(error => {
          //     console.log(error);
          //   });
          console.log(meetings);
          this.changeMeetings({
            meetings: meetings
          });
          that.$message({
            type: "success",
            meesage: "预定成功"
          });
          this.$router.push("/myreserve");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    ...mapMutations(["changeRooms", "changeMeetings"])
  }
};
</script>
<style scoped lang="scss">
h2 {
  text-align: left !important;
}
.formstyle {
  padding: 10px 20px;
  .ruleForm {
    margin-top: 20px;
    .collapsecontent {
      display: flex;
      .membername {
        width: 40px;
        height: 40px;
        text-align: center;
        margin: 0 3px;
        border: 1px solid #ccc;
        border-radius: 100%;
        font-size: 12px;
      }
    }
  }
}
.dialogcontent {
  .groupname {
    text-align: left;
    border-bottom: 1px solid rgb(235, 235, 235);
    padding-bottom: 5px;
  }
  .members {
    display: flex;
    margin-bottom: 15px;
    .memberitem {
      width: 40px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      margin: 0 3px;
      border: 1px solid #ccc;
      border-radius: 100%;
      font-size: 12px;
    }
  }
}
</style>
<style>
.el-form-item {
  text-align: left !important;
}
.line {
  text-align: center;
}
.at-collapse__icon {
  top: 20px !important;
}
</style>
